package com.lovo.manage_back.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lovo.manage_back.bean.Role;
import com.lovo.manage_back.bean.User;
import com.lovo.manage_back.dao.RoleMapper;
import com.lovo.manage_back.service.UserService;
import com.lovo.manage_back.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
* @author BDK-THINKPAD
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2023-08-02 09:25:50
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public PageInfo listUser(Integer current,Integer pageSize,User user) {
        PageHelper.startPage(current,pageSize);
        List<User> users = userMapper.listUser(null,null,user);
        return new PageInfo(users);
    }

    @Override
    public Map listUserRole(Integer id) {
        List<Role> allRoles = roleMapper.listRole();
        List<Role> assignRoles = roleMapper.listRoleByUserId(id);
        return Map.of("all",allRoles,"assign",assignRoles);
    }

    @Override
    public User getUserByName(String username) {
        return userMapper.getByUsername(username);
    }

    @Override
    public User login(User user) {
        return userMapper.getByUsernameAndPwd(user);
    }

    @Override
    @Transactional
    public int assignUserRole(Integer id, Integer[] roleIds) {
        roleMapper.deleteUserRoleByUserId(id);
        for(int i = 0;i < roleIds.length;i++){
            roleMapper.insertUserRole(id,roleIds[i]);
        }
        return 1;
    }

    @Override
    @Transactional
    public int deleteUser(Integer id) {
        roleMapper.deleteUserRoleByUserId(id);
        return userMapper.deleteById(id);
    }
}




